package com.sofwin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.dto.UserDto;
import com.sofwin.pojo.SDept;
import com.sofwin.pojo.SRole;
import com.sofwin.pojo.SUser;
import com.sofwin.service.DeptService;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;

@Controller
@RequestMapping("/system/user")
public class UserController {
	@Autowired
	private UserService service;
	@Autowired
	private DeptService deptService;
	@Autowired
	private RoleService roleService;
	
	/**
	 * 跳转到列表页
	 * 分页
	 * @return
	 */
	@RequestMapping("data")
	public ModelAndView data(SUser user,@RequestParam(required = true,defaultValue = "1")Integer pageNumber,@RequestParam(required = true,defaultValue = Constants.PAGE_SIZE)Integer pageSize) {
		PageInfo<UserDto> page = service.selectUserByPage(user, pageNumber, pageSize);
		ModelAndView mav = new ModelAndView("user/data");
		mav.addObject("page",page);
		mav.addObject("user", user);
		return mav;
	}
	@RequestMapping("/toEdit")
	public String toEdit(SUser user,Model model) {
		if(user.getId()!=null) {
			user = service.selectUserById(user.getId());
			model.addAttribute("user", user);
		}
		// 加载所有部门，并放入到request作用域中
		List<SDept> depts = deptService.listDepts();
		List<SRole> roles = roleService.listRoles();
		model.addAttribute("depts", depts);
		model.addAttribute("roles", roles);
		return "user/edit";
	}
	@RequestMapping("/save")
	@ResponseBody
	public Map save(SUser user) {
		Map map = new HashMap();
		Boolean status = service.saveOrUpdate(user);
		map.put("status",status );
		return map;
	}
	@RequestMapping("/delete")
	@ResponseBody
	public Map delete(SUser user) {
		Map map = new HashMap();
		Boolean status = service.deleteById(user.getId());
		map.put("status",status );
		return map;
	}
	@RequestMapping("deletes")
	@ResponseBody
	public Map deletes(String id) {
		Map map = new HashMap();
		String[] ids = id.split("~");
		Boolean status = service.deleteByIds(ids);
		map.put("status",status );
		return map;
	}
}
